package com.atguigu.tingshu.user.service.impl;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.*;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.user.strategy.StrategyFactory;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

	@Autowired
	private UserInfoMapper userInfoMapper;
	@Autowired
	private UserPaidAlbumMapper userPaidAlbumMapper;
	@Autowired
	private UserPaidTrackMapper userPaidTrackMapper;
	@Autowired
	private UserVipServiceMapper userVipServiceMapper;
	@Autowired
	private TrackInfoFeignClient trackInfoFeignClient;
	@Autowired
	private VipServiceConfigMapper vipServiceConfigMapper;
	@Autowired
	private StrategyFactory strategyFactory;
	@Override
	public List<Long> getPaidTrack(Long albumId, Long userId, List<Long> allTrackIdList) {
		// 查询用户是否购买该专辑
		UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>()
				.eq(UserPaidAlbum::getUserId, userId).eq(UserPaidAlbum::getAlbumId, albumId));
		if (userPaidAlbum != null){//用户购买了该专辑
			return allTrackIdList;
		}
		// 查询用户是否购买了该专辑的任意声音
		List<UserPaidTrack> paidTrackList = userPaidTrackMapper.selectList(new LambdaQueryWrapper<UserPaidTrack>()
				.eq(UserPaidTrack::getUserId, userId).eq(UserPaidTrack::getAlbumId, albumId));
		if (!CollectionUtils.isEmpty(paidTrackList)){
			return paidTrackList.stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
		}
		//用户未购买专辑或声音
		return null;
	}

	@Override
	public Boolean isPaidAlbum(Long userId, Long albumId) {
		return userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>()
				.eq(UserPaidAlbum::getUserId, userId)
				.eq(UserPaidAlbum::getAlbumId, albumId)) != null;
	}

	@Override
	public Boolean saveUserPaidRecord(UserPaidRecordVo userPaidRecordVo) {
		String itemType = userPaidRecordVo.getItemType();
		//计数器
		int count = 0;
		ItemTypeStrategy strategy = strategyFactory.getStrategy(itemType);
		count = strategy.savePaidRecord(userPaidRecordVo);
		return count>0;
	}

}
